package com.sk.waste.app.activitys

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RadioGroup
import android.widget.Spinner
import android.widget.TextView
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.UserModel
import com.sk.waste.app.utils.OkHttpUtil
import com.sking.album.utils.SKRPhotoSelectUtil
import com.sking.album.view.AlbumSelectPopuWindow
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException

/**
 *  @time 2025/4/25  17:11
 *  @desc 注册 修改信息
 */
class RegisterActivity : BaseActiivity() {

    private lateinit var imgUserAvatar: ImageView

    @LCBindView(R.id.ac_login_page_title)
    private lateinit var ttvPage: TextView

    @LCBindView(R.id.ac_register_user)
    private lateinit var ettUser: EditText

     @LCBindView(R.id.ac_register_name)
    private lateinit var ettName: EditText

    @LCBindView(R.id.ac_register_pass)
    private lateinit var ettPass: EditText

    @LCBindView(R.id.ac_register_phone)
    private lateinit var ettPhone: EditText

    @LCBindView(R.id.ac_register_code)
    private lateinit var ettCode: EditText

    @LCBindView(R.id.ac_register_getcode)
    private lateinit var bttCode: Button

    @LCBindView(R.id.ac_register_adress)
    private lateinit var ettAdress: EditText

    @LCBindView(R.id.ac_register_netadress)
    private lateinit var ettNetAdress: EditText

    @LCBindView(R.id.ac_register_introduct)
    private lateinit var ettIntroduct: EditText

    @LCBindView(R.id.ac_register_bussiness)
    private lateinit var ettBusiness: EditText

    @LCBindView(R.id.ac_register_radiogroup)
    private lateinit var radioGroup: RadioGroup

    @LCBindView(R.id.ac_register_layout)
    private lateinit var topLayout: LinearLayout

    @LCBindView(R.id.ac_register_midelayout)
    private lateinit var merchantLayout: LinearLayout

    @LCBindView(R.id.ac_register_spinner)
    private lateinit var spinnerProperty: Spinner

    @LCBindView(R.id.ac_register_submit)
    private lateinit var bttSubmit: Button

    private var countdown = 60
    private var handlerCountdown: Handler? = null

    private var userInfo: UserModel? = null
    private var pageType: Int = 0 // 0注册，1修改信息
    private var userType: Int = 0 //


    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_regitster)
        super.onCreate(savedInstanceState)
        setTitleColorLight(false)
        initView()
    }

    private fun initView() {
        setBack()
        pageType = intent.getIntExtra("extral_page", 0)
        radioGroup.setOnCheckedChangeListener { radioGroup, id ->
            when (id) {
                R.id.ac_register_people -> {
                    userType = 0
                    merchantLayout.visibility = View.GONE
                }

                R.id.ac_register_merchant -> {
                    userType = 1
                    merchantLayout.visibility = View.VISIBLE
                }
            }
        }

//        val adapter = ArrayAdapter(this, R.array.spinner_property,list) // 使用自定义布局
        val adapter = ArrayAdapter.createFromResource(this, R.array.spinner_property, R.layout.view_spinner_item) // 使用自定义布局
        adapter.setDropDownViewResource(R.layout.view_spinner_item_dropdown)
        spinnerProperty.adapter = adapter

        if (pageType != 0) {
            ttvPage.text = "修改资料"
            setUserInfo()
        }

        bttCode.setOnClickListener {
            val phone = ettPhone.text.toString().trim()
            if (isNull(phone)) {
                showToast("请输入手机号！")
                return@setOnClickListener
            }
            getCode(phone)
        }

        bttSubmit.setOnClickListener {
            var url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_REGISTER
            if (pageType != 0) {
                url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_USERUPDATE
            }
            val params = JSONObject()
            if (pageType == 0) {
                if (userType == 0) {
                    params.put("userType", "个人")
                } else {
                    params.put("userType", "商家")
                }
                params.put("account", ettUser.text.toString().trim())
                params.put("nickName", ettName.text.toString().trim())
                params.put("password", ettPass.text.toString().trim())
                params.put("phone", ettPhone.text.toString().trim())
                params.put("captcha", ettCode.text.toString().trim())
//                params.put("captcha", "199999")
            }
            if (pageType == 1) {
                params.put("account", userInfo?.account)
                params.put("phone", userInfo?.phone)
            }
            params.put("nickName", ettName.text.toString())
            params.put("address", ettAdress.text.toString())
            if (userType != 0) {
                params.put("companyNature", spinnerProperty.selectedItem.toString().trim())
                params.put("companyWebsite", ettNetAdress.text.toString().trim())
                params.put("companyIntroduction", ettIntroduct.text.toString().trim())
                params.put("mainBusiness", ettBusiness.text.toString().trim())

            }
            registSubmit(url, params.toString())
        }
    }

    /**
     *  @time 2025/6/7  11:23
     *  @desc 设置信息
     */
    private fun setUserInfo() {
        radioGroup.visibility = View.GONE
        topLayout.visibility = View.GONE
        ettUser.visibility = View.GONE
        userInfo = MyApplication.instance.getUserInfo()
        setTextValue(ettName, userInfo?.nickName)
        setTextValue(ettAdress, userInfo?.address)

        if (userInfo?.userType == "个人") {
            userType = 0
            radioGroup.check(R.id.ac_register_people)
        } else {
            userType = 1
            radioGroup.check(R.id.ac_register_merchant)

            val arrays = resources.getStringArray(R.array.spinner_property)
            for (index in arrays.indices) {
                if (arrays[index] == userInfo?.companyNature) {
                    spinnerProperty.setSelection(index)
                    break
                }
            }
            setTextValue(ettNetAdress, userInfo?.companyWebsite)
            setTextValue(ettIntroduct, userInfo?.companyIntroduction)
            setTextValue(ettBusiness, userInfo?.mainBusiness)
        }
    }

    /**
     *  @time 2025/6/6  19:25
     *  @desc 校验参数
     */
    private fun checkParams(): Boolean {
        if (pageType != 0)
            return true

        val userAccount = ettUser.text.toString()
        if (isNull(userAccount)) {
            showToast("请输入登录账户！")
            return false
        }
        val userName = ettName.text.toString()
        if (isNull(userName)) {
            showToast("请输入用户昵称！")
            return false
        }
        val userPass = ettPass.text.toString()
        if (isNull(userPass)) {
            showToast("请输入密码！")
            return false
        }
        val regex = "^(?=.*[A-Za-z])(?=.*\\d).+$"
        if (userPass.length < 6 || !userPass.matches(Regex(regex))) {
            showToast("请输入6位以上的密码，包含字母和数字！")
            return false
        }

        val userPhone = ettPhone.text.toString()
        if (isNull(userPhone)) {
            showToast("请输入手机号！")
            return false
        }

        val userCode = ettCode.text.toString()
        if (isNull(userCode)) {
            showToast("请输入验证码！")
            return false
        }

        val userAdress = ettAdress.text.toString()
        if (isNull(userAdress)) {
            showToast("请输入地址！")
            return false
        }

        if (userType != 0) {
//            val companyNetAdress = ettNetAdress.text.toString()
//            if (isNull(companyNetAdress)) {
//                showToast("请输入公司官网！")
//                return false
//            }

            val companyIntroduct = ettIntroduct.text.toString()
            if (isNull(companyIntroduct)) {
                showToast("请输入公司介绍！")
                return false
            }
            val companyBusiness = ettBusiness.text.toString()
            if (isNull(companyBusiness)) {
                showToast("请输入主营业务！")
                return false
            }
        }
        return true
    }

    /**
     *  @time 2024/5/11  18:16
     *  @author Im_jingwei
     *  @desc 倒计时
     */
    private fun startCountdown() {
        handlerCountdown = Handler(Looper.getMainLooper())
        handlerCountdown?.postDelayed(handRunnableReped, 1000)
    }

    private val handRunnableReped = object : Runnable {
        override fun run() {
            countdown--
            runOnUiThread {
                bttCode.isEnabled = false
                bttCode.text = countdown.toString() + "秒"
            }
            if (countdown > 0) {
                handlerCountdown?.postDelayed(this, 1000)
            } else {
                countdown = 60
                bttCode.isEnabled = true
                bttCode.text = "获取验证码"
            }
        }
    }

    /**
     *  @time 2025/6/6  19:41
     *  @desc 获取验证码
     */
    private fun getCode(phone: String) {
        showProgress()
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_GETCODE
        val params = JSONObject()
        params.put("phone", phone)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("发送失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    runOnUiThread { startCountdown() }
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        showToast("验证码已发送,请注意查收！")
                        LCLogger.d(TAG, "发送成功！,信息：$jsonObject")
                    } else {
                        showToast("发送失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("发送失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/6/6  19:41
     *  @desc 提交
     */
    private fun registSubmit(url: String, params: String) {
        if (!checkParams()) return
        showProgress()
        val httpUtil = OkHttpUtil()
        var token: String? = null
        if (pageType == 1) {
            token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        }
        httpUtil.httpRequest(url, token, params, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("注册失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        if (pageType != 1) {
                            showToast("注册成功,请登录！")
                            toLogin()
                        } else {
                            showToast("修改成功！")
                            finish()
                        }
                        LCLogger.d(TAG, "注册成功！,信息：$jsonObject")
                    } else {
                        if (pageType != 1) {
                            showToast("修改失败，$msg")
                        } else {
                            showToast("注册失败，$msg")
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("注册失败，" + e.message)
                }
            }
        })
    }

    private fun toLogin() {
        val intent = Intent(mContext, LoginActivity::class.java)
        startActivity(intent)
        finish()
    }



}